import { Injectable } from '@nestjs/common';
import { UserService } from 'src/user/user.service';
import { JwtService } from '@nestjs/jwt';
import { jwtConstants } from './constants';

@Injectable()
export class AuthService {
    constructor(
        private readonly userService: UserService,
        private readonly jwtService: JwtService
    ) { }

    async validateUser(name: string, pass: string): Promise<any> {
        const user = await this.userService.findOne(name);
        if (user && user.user_pass === pass) {
            const { user_pass, ...result } = user;
            return result;
        }
        return null;
    }

    async login(user: any) {
        const payload = { id: user.id, name: user.name, roles: user.roles };
        return {
            code: 200,
            message: "success",
            id: payload.id,
            name: payload.name,
            access_token: this.jwtService.sign(payload)
        };
    }
}
